import { IncomingMessage } from "http";
import { Response } from "./rest_response";

interface Interceptor {
    processResonse(req: IncomingMessage, response: Response): void;
}

class AllowCrossDomain implements Interceptor {
    allowOrigin: string;
    allowMethods?: string;
    constructor(origin: string, methods?: string[]) {
        this.allowOrigin = origin;

        if (methods && methods.length > 0) {
            this.allowMethods = methods.join(",");
        }
    }
    processResonse(req: IncomingMessage, response: Response): void {
        if (req.headers.origin) {
            response.headers["Access-Control-Allow-Credentials"] = "true";
            response.headers["Access-Control-Allow-Origin"] =
                req.headers.origin;
        }
        if (req.method == "OPTIONS") {
            response.headers["Access-Control-Allow-Methods"] =
                response.headers["Allow"];
            response.headers["Access-Control-Allow-Headers"] = "content-type";
        }
    }
}

export { Interceptor, AllowCrossDomain };
